<?php
/**
 * @file upgrade.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年8月31日 下午4:10:56 $
 * @brief 升级提示 $
 */
namespace haibao\app\business;

use haibao\frame\FrameException;
class AppUpgrade extends \haibao\app\business\Base{
    
    /**
     * @var $_instance
     */
    private static $_instance;
    
    /**
     * instance()
     */
    private static function instance(){
        if(!self::$_instance){
            self::$_instance = new \haibao\app\data\AppUpgrade();
        }
        return self::$_instance;
    }
    
    /**
     * 根据ID查询升级提示
     */
    public static function getUpgradeById($id){
        return self::instance()->getUpgradeById($id);
    }
    
    /**
     * 根据手机类型查询最高版本APP应用
     */
    public static function getUpgradeByAppType($appType){
        if(!$appType){
            throw new BusinessException('参数不正确', \haibao\app\business\Base::DATA_ERROR_CODE_EMPTY);
        }
        if($appType != \haibao\app\model\data\PhoneInfo::OS_TYPE_ANDROID && $appType != \haibao\app\model\data\PhoneInfo::OS_TYPE_IOS){
            throw new BusinessException('参数不正确', \haibao\app\business\Base::DATA_ERROR_CODE_EMPTY);
        }
        return self::instance()->getUpgradeByAppType($appType);
    }
    
    /**
     * 升级提示query
     */
    public static function getUpgradeByQuery($query){
        return self::instance()->getAll($query);
    }
    
    /**
     * 保存升级提示
     * @param \haibao\app\model\data\AppUpgrade $model
     */
    public static function saveUpgrade($model){
        self::checkOperation(self::FUNC_CODE_APP_SYSTEM_MESSAGE_ADD);
        self::checkForm($model);
        $model->CreateBy = self::getCurrentUser()->Id;
        $model->CreateTime = new \DateTime();
        $model->Status = \haibao\app\model\data\AppUpgrade::STATUS_ENABLE;
        self::instance()->saveUpgrade($model);
        self::saveOperateHistory(self::FUNC_CODE_APP_SYSTEM_MESSAGE_ADD, $model->toArray(true,true));
    }
    
    /**
     * 删除升级提醒记录
     */
    public static function deleteUpgrade($id){
        self::checkOperation(self::FUNC_CODE_APP_SYSTEM_MESSAGE_ADD);
        self::instance()->updateStatusById($id, \haibao\app\model\data\AppUpgrade::STATUS_DISABLE);
        self::saveOperateHistory(self::FUNC_CODE_APP_SYSTEM_MESSAGE_ADD, $id);
    }
    
    /**
     * 检查表单
     * @param \haibao\app\model\data\AppUpgrade $model
     */
    public static function checkForm($model){
        if(!$model->AppType){
            throw new BusinessException('平台不能为空');
        }
        if(!$model->Title){
            throw new BusinessException('标题不能为空');
        }
        if(!$model->Content){
            throw new BusinessException('内容不能为空');
        }
        if(!$model->Version){
            throw new BusinessException('版本号不能为空');
        }
    }
}